<template>
  <div>
    <el-upload
      action="#"
      :file-list="fileList"
      list-type="picture-card"
      :on-preview="onPreview"
      :on-remove="onRemove"
      :before-upload="beforeUpload"
      :on-change="onChange"
      :http-request="httpRequest"
      :class="{hasImage : fileList.length > 0}"
    >
      <i class="el-icon-plus" />
    </el-upload>

    <el-progress
      v-show="showPercent"
      :show-text="false"
      type="line"
      :percentage="percent"
      style="width:146px"
    />

    <el-dialog title="预览" :visible="showDialog" class="dialog__header" @close="closeDialog">
      <el-row type="flex" justify="center">
        <img :src="preView" alt="">
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import COS from 'cos-js-sdk-v5'
const cos = new COS({
  SecretId: 'AKIDZ2JMBnCNNBm9LK5dz97rOhohNp33sXzJ',
  SecretKey: 'A7sPinfLo58xYv51kFYeWAbppb9VdXDf'
})
export default {
  data() {
    return {
      fileList: [],
      showDialog: false,
      preView: '',
      currentFileUid: '',
      showPercent: false,
      percent: 0
    }
  },
  methods: {
    onPreview(file) {
      this.preView = file.url
      this.showDialog = true
    },
    onRemove(file, newfileList) {
      this.fileList = newfileList
    },
    beforeUpload(file) {
      const typeList = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif']
      if (!typeList.includes(file.type)) {
        this.$message.error('目前只支持png、jpeg、jpg、gif')
        return false
      }
      const maxSize = 1024 * 1024 * 5
      if (file.size > maxSize) {
        this.$message.error('图片不能大于5M')
        return false
      }

      //   已经确定当前上传的就是当前的这个file了
      this.currentFileUid = file.uid
      return true // 最后一定要return  true
    },
    onChange(file, fileList) {
      this.fileList = fileList
    },
    httpRequest(params) {
      this.showPercent = true
      cos.putObject({
        Bucket: 'hr-1309641514', /* 必须 */
        Region: 'ap-guangzhou', /* 存储桶所在地域，必须字段 */
        Key: params.file.name, /* 必须 */
        StorageClass: 'STANDARD',
        Body: params.file, // 上传文件对象
        onProgress: (progressData) => {
          console.log(JSON.stringify(progressData))
          this.percent = progressData.percent * 100
        }
      }, (err, data) => {
        console.log(err || data)
        this.fileList[0].url = 'http://' + data.Location
        this.fileList[0].status = 'success'
        setTimeout(() => {
          this.showPercent = false
        }, 1000)
      })
    },
    closeDialog() {
      this.showDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.dialog__header {
    ::v-deep .el-dialog__header{
        padding:0 10px ;
    }
}
.hasImage{
    ::v-deep .el-upload--picture-card{
        display: none;
    }
}
::v-deep img{
  width: 100%;
  object-fit: cover;
}
</style>
